type Context = WebGLRenderingContext | WebGL2RenderingContext;
export let gl: Context;
export function initializeGL(canvas: HTMLCanvasElement): boolean {
    let tgl = canvas.getContext("webgl2") || canvas.getContext('webgl');
    if (tgl == null) {
        console.log("failed to get WebGL rednering context");
        return false;
    }
    gl = tgl;
    return true;
}

export function initShaders(gl: Context, vShader: string, fShader: string): WebGLProgram | null {
    let vs = loadShader(gl, gl.VERTEX_SHADER, vShader);
    let fs = loadShader(gl, gl.FRAGMENT_SHADER, fShader);
    if (!vs || !fs) {
        return null;
    }

    let program = gl.createProgram()
    if (!program) {
        return null;
    }
    gl.attachShader(program, vs);
    gl.attachShader(program, fs);
    gl.linkProgram(program);
    let linked = gl.getProgramParameter(program, gl.LINK_STATUS);
    if (!linked) {
        let err = gl.getProgramInfoLog(program);
        console.log('Falied to link program', err);
        gl.deleteProgram(program);
        gl.deleteShader(vs);
        gl.deleteShader(fs);
        return null;
    }
    return program;
}

function loadShader(gl: Context, type: number, source: string): WebGLShader | null {
    let shader = gl.createShader(type);
    if (null == shader) {
        console.log("Unable to create shader");
        return null;
    }
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    let compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
    if (!compiled) {
        let err = gl.getShaderInfoLog(shader);
        console.log('Falied to compile shader:', err);
        gl.deleteShader(shader);
        return null;
    }
    return shader;
}